<template>
    <div class="dashboard">
        <div class="main-head has-radios flex-between container-fluid">
            <div class="title">
                <h1>
                    {{$t('pro.public.header.Dashboard')}}
                </h1>
            </div>
            <a-radio-group v-model="rdChecked" buttonStyle="solid" @change="handleCheckedChange">
                <a-tooltip
                   placement="top"
                   :title="$t('pro.public.home.dateTitle')"
                   class="tips-data"
                   :overlayClassName="'tips-data'"
                   :getPopupContainer="getPopupContainer"
                >
                    <a-icon type="question-circle"/>
                </a-tooltip>
                <a-spin :spinning="spinningDate" class="dsp-spin">
                     <a-radio-button v-for="(value,key) in radios" :key="key" :value="value[0]">{{value[1]}}</a-radio-button>
                </a-spin>
            </a-radio-group>
        </div>
        <div class="content container-fluid">
            <div class="text-right m-b">
                <a-range-picker
                        style="width: 337px;"
                        :format="dataformat"
                        @change="handleDatePickerChange"
                        v-show="rdChecked==='getCustom'"
                        @openChange="openChange"
                />
            </div>
            <div class="grid top">
                <!-- Impressions  -->
                <div class="grid-item">
                    <div class="display flex-between">
                        <div class="number">
                            <h3 style="color: #2AB4C0">
                                <number-grow :value="impressions.impressions" :places="0"></number-grow>
                            </h3>
                            <small class="uppercase" v-text="$t('pro.dashboard.impressions')"></small>
                        </div>
                        <div class="icon">
                            <span class="iconfont icon-users icon-color"></span>
                        </div>
                    </div>
                    <div class="progress-info">
                        <div class="status flex-between">
                            <div class="status-name">eCPM</div>
                            <div class="status-data">{{impressions.eCPM}}</div>
                        </div>
                        <div class="status flex-between" v-show="getDashboardDay">
                            <div class="status-name font-all-uppercase" v-text="getDashboardDay"></div>
                            <div class="status-data">{{impressions.yesterday}}</div>
                        </div>
                    </div>
                </div>

                <!-- CLICKS & CONVERSIONS & ECPA 开始 -->
                <div class="grid-item">
                    <div class="display flex-between">
                        <div class="number">
                            <h3 style="color: #8877A9">
                                <number-grow :value="cliks.cliks"></number-grow>
                            </h3>
                            <small class="uppercase" v-text="$t('pro.dashboard.click')"></small>
                        </div>
                        <div class="number">
                            <h3>{{cliks.conversions}}</h3>
                            <small class="uppercase" v-text="$t('pro.dashboard.conversions')"></small>
                        </div>

                        <div class="icon">
                            <span class="iconfont icon-baifenhao icon-color"></span>
                        </div>
                    </div>
                    <div class="progress-info">
                        <div class="status flex-between">
                            <div class="status-name no-transform">eCPC</div>
                            <div class="status-data">{{cliks.eCPA}}</div>
                        </div>
                        <div class="status flex-between">
                            <div class="status-name no-transform">CTR</div>
                            <div class="status-data">{{cliks.CTR}}</div>
                        </div>
                        <div class="status flex-between" v-show="getDashboardDay">
                            <div class="status-name font-all-uppercase" v-text="getDashboardDay"></div>
                            <div class="status-data">{{cliks.yesterday}}</div>
                        </div>
                    </div>
                </div>

                <!-- SPEND  -->
                <div class="grid-item">
                    <div class="display flex-between">
                        <div class="number">
                            <h3 style="color: #578EBE">
                                <span>$</span>
                                <number-grow :value="spend.spend"></number-grow>
                            </h3>
                            <small class="uppercase" v-text="$t('pro.dashboard.spend')"></small>
                        </div>
                        <div class="icon">
                            <span class="iconfont icon-ziyuan icon-color"></span>
                        </div>
                    </div>
                    <div class="progress-info">
                        <div class="status flex-between" v-show="getDashboardDay">
                            <div class="status-name font-all-uppercase" v-text="getDashboardDay"></div>
                            <div class="status-data">${{spend.yesterday}}</div>
                        </div>
                    </div>
                </div>

                <!-- BALANCE  -->
                <div class="grid-item">
                    <div class="display flex-between">
                        <div class="number">
                            <h3 style="color: #61A6DB;">
                                <span>$</span>
                                <number-grow :value="balance.balance"></number-grow>
                            </h3>
                            <small class="uppercase" v-text="$t('pro.dashboard.yourBalance')"></small>
                        </div>
                        <div class="icon">
                            <span class="iconfont icon-meiyuan4 icon-color"></span>
                        </div>
                    </div>
                    <div class="progress-info">
                        <div class="status flex-between">
                            <router-link to="/billing/billing">{{ $t('pro.dashboard.a1') }}</router-link>
                        </div>
                        <div class="status flex-between">
                            <router-link to="/billing/transactionhistory">{{ $t('pro.dashboard.a2') }}</router-link>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid bottom">
                <div class="grid-item">
                    <div class="portlet-title">
                        <a-icon type="bar-chart" class="title-top-icon"/>

                        <span class="uppercase title-text" v-text="$t('pro.dashboard.Advertising_Activities')"></span>&nbsp;
                        <span v-text="$t('pro.dashboard.topFive')"></span>
                    </div>
                    <!-- 活动系列 -->
                    <div class="portlet-body">
                        <div class="number-status grid">
                            <div class="number-status-l">
                                <div class="number-status-title" v-text="$t('pro.dashboard.totalImpressions')"></div>
                                <div class="data">{{ pixelsCampaigns | numberFormat }}</div>
                                <!-- 图表 -->
                                <div class="echarts-box chart1">
                                    <chart
                                            class="chart-assembly"
                                            ref="chart1"
                                            :options="chartPixelsCampaigns"
                                            :auto-resize="true"
                                    ></chart>
                                </div>
                            </div>

                            <div class="number-status-r">
                                <div class="number-status-title" v-text="$t('pro.dashboard.totalSpend')"></div>
                                <div class="data">{{ totalSpendCampaigns | decimalFormat}}</div>
                                <div class="echarts-box chart2">
                                    <chart
                                            class="chart-assembly"
                                            ref="chart2"
                                            :options="chartTotalSpendCampaigns"
                                            :auto-resize="true"
                                    ></chart>
                                </div>
                            </div>
                        </div>
                        <div class="bottom-table">
                            <a-table
                                    v-if="!!dataCampaigns && dataCampaigns.length>0"
                                    :pagination="false"
                                    :columns="columns"
                                    :dataSource="dataCampaigns"
                                    :scroll="{ x: 600 }"
                                    :loading="dataCampaignsLoading"
                            >
                                <router-link :to="'/reports/campaigns/'+item.id" slot="action"slot-scope="item">
                                    <a-icon type="search" class="icon-search"/>
                                </router-link>
                            </a-table>
                            <div v-else>
                                <a-empty
                                        image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                                    <span slot="description">{{$t('pro.campaigns.activeNotMess')}}</span>
                                </a-empty>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="grid-item">
                    <div class="portlet-title">
                        <a-icon type="bar-chart" class="title-top-icon"/>
                        <span class="uppercase title-text" v-text="$t('pro.dashboard.activity')"></span>&nbsp;
                        <span v-text="$t('pro.dashboard.topFive')"></span>
                    </div>
                    <div class="portlet-body">
                        <div class="number-status grid">
                            <div class="number-status-l">
                                <div class="number-status-title" v-text="$t('pro.dashboard.totalImpressions')"></div>
                                <div class="data">{{ pixelsCreatives | numberFormat}}</div>

                                <div class="echarts-box chart1">
                                    <chart
                                            class="chart-assembly"
                                            ref="chart3"
                                            :options="chartPixelsCreatives"
                                            :auto-resize="true"
                                    ></chart>
                                </div>
                            </div>
                            <div class="number-status-r">
                                <div class="number-status-title" v-text="$t('pro.dashboard.totalSpend')"></div>
                                <div class="data">{{ totalSpendCreatives | decimalFormat }}</div>

                                <div class="echarts-box chart2">
                                    <chart
                                        class="chart-assembly"
                                        ref="chart4"
                                        :options="chartTotalSpendCreatives"
                                        :auto-resize="true"
                                    ></chart>
                                </div>
                            </div>
                        </div>
                        <div class="bottom-table">
                            <a-table
                                    v-if="!!dataCreatives && dataCreatives.length>0"
                                    :pagination="false"
                                    :columns="columns"
                                    :dataSource="dataCreatives"
                                    :scroll="{ x: 600 }"
                                    :loading="dataCreativesLoading"
                            >
                                 <a-icon type="search" slot="action" slot-scope="item" @click="toReports(item.id)" class="icon-search"/>
                            </a-table>
                            <div v-else>
                                <a-empty
                                        image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                                    <span slot="description">{{$t('pro.campaigns.activeNotMess')}}</span>
                                </a-empty>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import numberGrow from "../components/common/custom/NumberGrow";
    import {formatMoney} from "../utils/tool";

    import {
        getCampaignsByTo,
        getCampaignsCreativeByTop,
        getReport
    } from "../api";
    import {getBalance} from "../api/user";

    export default {
        name: "dashboard",
        components: {numberGrow},
        filters: {
            numberFormat(value) {
                return formatMoney(value, 0, "");
            },
            decimalFormat(number) {
                return formatMoney(number, 2, "$");
            }
        },
        data() {
            return {
                spinningDate: false,
                selectData: [],

                pixelsCampaigns: 0, //总印象
                totalSpendCampaigns: 0, //总支出
                dataCampaigns: [],
                dataCampaignsLoading: false,
                chartPixelsCampaigns: {},
                chartTotalSpendCampaigns: {},

                pixelsCreatives: 0,
                totalSpendCreatives: 0,
                dataCreatives: [],
                dataCreativesLoading: false,
                chartPixelsCreatives: {},
                chartTotalSpendCreatives: {},

                rdChecked: "getThisWeek", //默认选择 所有
                // 此数据用于记录用户点击`getCustom`之前this.rdChecked值
                // 在生命周期mounted中重新赋值默认值:day
                rdCheckedWithoutgetCustom: "",
                dataformat: "YYYY-MM-DD",

                impressions: {
                    impressions: 99,
                    eCPM: "-",
                    yesterday: "",
                },
                cliks: {
                    cliks: 0,
                    conversions: 0,
                    eCPA: "-",
                    eCPC: "-",
                    CTR: "-",
                    yesterday: "0 (0%)",
                },
                spend: {
                    spend: 0,
                    yesterday: "0 (0%)",
                },
                balance: {
                    balance: 0
                }
            };
        },
        computed: {
            gethtml() {
              return `<p class=empty">{{$t("pro.campaigns.activeNotMess")}}
                            <router-link to="/bidder/editcampaign">
                                <a-button size="small" type="primary"><a-icon type="plus" /></a-button>
                            </router-link>
                            </p>`
            },
            // 这里处理预设日期范围（Today，This week...）期限内的第一天和最后一天
            period() {
                const firstday = this.$moment().startOf(this.rdChecked);
                const lastday = this.$moment().endOf(
                    this.rdChecked === "lifetime" ? "day" : this.rdChecked
                );
                return [firstday, lastday];
            },

            // 用户需自定义日期期限时，DatePicker的默认值
            datePickerDefaultValue() {
                const firstday = this.$moment().startOf(this.rdCheckedWithoutgetCustom);
                const lastday = this.$moment().endOf(this.rdCheckedWithoutgetCustom);
                return [firstday, lastday];
            },

            columns() {
                return this.$t("pro.dashboard.columns");
            },
            radios() {
                return new Map(this.$t("pro.public.radiosDate"));
            },
            //根据筛选不同切换日期显示
            getDashboardDay(){
                let str = ""
                if (this.rdChecked != "getCustom" ||  this.rdChecked != "getAll") {
                    switch (this.rdChecked) {
                        case "getToDay":
                            str = this.$t('pro.dashboard.yesterday');
                            break;
                        case "getThisWeek":
                            str = this.$t('pro.dashboard.LastWeek');
                            break;
                        case "getThisMounth":
                            str = this.$t('pro.dashboard.LastMonth');
                            break;
                        case "getThisYear":
                            str = this.$t('pro.dashboard.LastYear');
                            break
                    }
                }
                return str
            }
        },
        methods: {
            toReports(id) {
                this.$router.push({ path: '/reports/creative/'+id })
            },
            //提示用户筛选时间自动适应位置 挂载到父元素
            getPopupContainer(trigger) {
                return trigger.parentElement;
            },
            /* 时间筛选 */
            handleDatePickerChange(value, mode) {
                this.selectData = mode;
            },
            openChange(status) {
                this.$nextTick(() => {
                    if (!status) {
                        this.selectData = this.selectData.map((item, index) => {
                            item = item+"";
                            if (index === 0) {
                                item = item.includes('00:00:00') ? item : item + ' 00:00:00' 
                            }else {
                                item = item.includes('23:59:59') ? item : item + ' 23:59:59' 
                            }
                            return item
                        });
                        this.findCampaignsByTop();
                        this.findCampaignsCreativeByTop();
                        this.findReport();
                    }
                })
            },

            handleCheckedChange() {
                // 使用计算属性下的```period```获取服务器端数据
                if (this.rdChecked != "getCustom") {
                    this.spinningDate = true;
                    this.findCampaignsByTop();
                    this.findCampaignsCreativeByTop();
                    this.findReport();
                    this.initData();

                    setTimeout(() => {
                        this.spinningDate = false;
                    }, 930);
                }
            },

            //查询广告活动排行榜
            findCampaignsByTop() {
                let params = this.publicParams();
                this.dataCampaignsLoading = true;
                setTimeout(() => {
                    getCampaignsByTo(params)
                        .then(res => {
                            let {data, code} = res.data;
                            //totalSpendCampaigns
                            if (code == 200) {
                                this.publicEchartComputed(data, 'dataCampaigns', 'pixelsCampaigns', 'totalSpendCampaigns', 'chartPixelsCampaigns', 'chartTotalSpendCampaigns')
                            }
                        }).finally(() => {
                        this.dataCampaignsLoading = false
                    })
                }, 500);
            },

            //查询广告系列
            findCampaignsCreativeByTop() {
                this.dataCreativesLoading = true;
                let params = this.publicParams();
                setTimeout(() => {
                    getCampaignsCreativeByTop(params)
                        .then(res => {
                            let {data, code} = res.data;
                            if (code == 200) {
                                this.publicEchartComputed(data, 'dataCreatives', 'pixelsCreatives', 'totalSpendCreatives', 'chartPixelsCreatives', 'chartTotalSpendCreatives')
                            }
                        }).finally(() => { this.dataCreativesLoading = false })
                }, 500);
            },

            findReport() {
                let params = this.publicParams()
                getReport(params).then(res => {
                    let {code, data} = res.data;
                    if (code == 200) {
                        //昨天
                        this.impressions.yesterday = data.bids.old || 0;
                        this.cliks.yesterday = +((data.wins.old || 0) / (data.bids.old || 0)).toFixed(2)
                        this.cliks.yesterday = Number.isNaN(this.cliks.yesterday) ? 0 : this.cliks.yesterday

                        this.spend.yesterday = Math.floor((data.wins_price.old || 0) * 100) / 100;

                        //今天
                        this.impressions.impressions =   +data.bids['this'] || 0;
                        this.cliks.cliks = ((+data.wins['this'] || 0) / (+data.bids['this'] || 0)) * 100 ;

                        this.spend.spend = +data.wins_price['this'] || 0;
                    }
                });
            },
            /***
             * 获取接口数据后 处理对应数据渲染给页面数据
             * @param data 后端时间
             * @param table table需要存储数据
             * @param pixels 总展示次数
             * @param total 总支出
             * @param chartPixels 图表总展示次数
             * @param chartTotal 图表总支出
             */
            publicEchartComputed(data, table, pixels, total, chartPixels, chartTotal) {
                let length = data.length || 0;
                let pixelsAvg = 0
                let totalAvg = 0;

                //存储循环之后 给图表配置的临时变量
                let pixelsSeries = [];
                let totalSpendSeries = [];

                //页面数据
                this[table] = [];
                this[pixels] = 0;
                this[total] = 0;

                for (let i = 0; i < length; i++) {
                    let winsPrice = data[i].winsPrice;
                    let params = {
                        key: data[i].id,
                        id: data[i].id,
                        name: data[i].name,
                        pixels: data[i].pixels,
                        wins: data[i].wins,
                        bids: data[i].bids,
                        winsPrice: Math.floor(winsPrice * 100) / 100,
                    };

                    this[table].push(params);

                    //图表需要的配置数据
                    pixelsSeries.push(params.pixels);
                    totalSpendSeries.push(params.winsPrice);

                    //总印象次数
                    this[pixels] += Number.parseFloat(params.pixels);
                    //总支出
                    this[total] += Number.parseFloat(winsPrice)
                    if (i==(length-1)){
                        this[total]=Math.floor(this[total] * 100) / 100;
                    }
                    //计算平均数
                    pixelsAvg += !!params.pixels;
                    totalAvg += !!params.winsPrice;
                }

                //图表 条形图
                this[chartPixels].series[0].data = pixelsSeries;
                this[chartTotal].series[0].data = totalSpendSeries;

                //图表计算 平均值
                this[chartPixels].yAxis[0].max = (this[pixels] / pixelsAvg).toFixed(0);
                this[chartTotal].yAxis[0].max =  (this[total] / totalAvg).toFixed(0) ;
            },

            publicParams() {
                return {
                    time: this.rdChecked,
                    start: this.selectData[0],
                    end: this.selectData[1]
                };

            },

            initData() {
                //余额
                getBalance().then(res => {
                    let {code, data} = res.data || {};
                    if (code == 200) {
                        this.balance.balance = data.surplus_amount || 0;
                    }
                });
            }
        },

        created() {
            //请求余额花费
            this.initData();
            //前3个统计
            this.findReport();

            setTimeout(() => {
                //手动 静态数据
                this.cliks.cliks = 0;
            }, 360);

            /* 图表默认配置 */
            const defaultEChart = {
                xAxis: [
                    {
                        type: "category",
                        data: ["", "", "", "", ""]
                    }
                ],
                yAxis: [
                    {
                        type: "value",
                        show: false,
                        splitLine: {show: false},
                        max: 1000
                    }
                ],
                grid: {
                    left: "5%",
                    right: "0%",
                    bottom: "0%",
                    containLabel: false
                },
                series: [
                    {
                        name: "",
                        data: [],
                        type: "bar",
                        barWidth: "55%"
                    }
                ]
            };

            /* 活动系列*/
            this.chartPixelsCampaigns = JSON.parse(JSON.stringify(defaultEChart));
            this.chartPixelsCampaigns.color = ["#61BC6D"];

            this.chartTotalSpendCampaigns = JSON.parse(JSON.stringify(defaultEChart));
            this.chartTotalSpendCampaigns.color = ["#FFCD43"];


            /* 广告活动*/
            this.chartPixelsCreatives = JSON.parse(JSON.stringify(defaultEChart));
            this.chartPixelsCreatives.color = ["#61BC6D"];

            this.chartTotalSpendCreatives = JSON.parse(JSON.stringify(defaultEChart))
            this.chartTotalSpendCreatives.color = ["#FFCD43"];
        },

        mounted() {
            this.findCampaignsByTop();
            this.findCampaignsCreativeByTop();

            
        }
    };
</script>

<style lang="less">
    .dark .ant-tooltip-inner {
        color: #333!important;
        background: #FFFFFF!important;
    }
    .dark .ant-tooltip-placement-top .ant-tooltip-arrow {
        border-top-color: #fff!important;;
    }
</style>

<style lang="less" scoped>
    // @import "@/assets/css/colors.scss";
    .icon-color {
        color: #cbd4e0;
        font-size: 30px;
    }

    .icon-search {
        font-size: 18.5px;
    }

    .tips-data {
        margin-right: 0.6rem;
        color: red;
    }

    .grid-item .progress-info, .display {
        color: #AAB5BC !important;
        font-weight: 600 !important;
    }

    .number-status-title {
        color: #888888;
    }

    h1,
    h3 {
        margin-bottom: 0;
    }

    .grid {
        grid-gap: 10px;
    }

    .grid.top {
        margin-bottom: 2rem;
        .grid-item .flex-between {
            flex-wrap: wrap-reverse;
        }
    }

    // 头部栅格布局
    @media screen and (min-width: 992px) {
        .grid.top {
            grid-template-columns: repeat(4, 1fr);
        }
    }

    @media screen and (max-width: 992px) {
        .grid.top {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    // 底部栅格布局
    @media screen and (min-width: 769px) {
        .grid.bottom {
            grid-template-columns: repeat(2, calc(50% - 5px));
        }
    }

    @media screen and (max-width: 768px) {
        .grid.top {
            grid-template-columns: repeat(1, 1fr);
        }

        .grid.bottom {
            grid-template-columns: repeat(1, 100%);
        }

        .tips-data {
            margin-right: 22.6rem;
        }
        .ant-spin-container {
            background-color: #eb2f96;
        }
    }

    @media screen and (max-width: 800px) {
        .tips-data {
            margin-right: 0.6rem;
        }
        .ant-spin-container {
            background-color: #eb2f96;
        }
    }

    .grid .grid-item {
        padding-left: 15px;
        padding-right: 15px;
        background-color: #fff;
    }

    .grid.top .grid-item {
        padding-top: 15px;
        padding-bottom: 15px;
    }

    .display {
        margin-bottom: 20px;
        .number {
            h3 {
                font-size: 1.6rem;
                span {
                    font-size: 0.7em;
                }
            }
            small {
                font-size: 1.1rem;
            }
        }
    }

    .portlet-title {
        border-bottom: 1px solid #eee;
        padding: 1.111111rem 0;
        .title-text {
            font-weight: bold;
            color: #e7505a;
        }
        .title-top-icon {
            color: #e7505a;
            font-size: 1.4rem;
            margin-right: 8px;
        }
    }

    /* 底部盒子 */
    .portlet-body {
        padding: 20px 0;
    }

    .number-status {
        grid-gap: 1px;
        grid-template-columns: repeat(2, 1fr);

        .data {
            font-size: 1.7em;
            font-weight: 500;
            color: #928c9d;
            span {
                font-size: 0.7em;
            }
        }
    }

    .number-status-l {
        padding-right: 70px;
        text-align: right;
        position: relative;
    }

    .echarts-box {
        position: absolute;
        bottom: 0;
        height: 70px;
        width: 50px;
        z-index: 99999;
        /* 解决图表超出 缺点：没有鼠标悬浮*/
        overflow: hidden;
        .chart-assembly {
            width: 50px;
            height: 100px;
            position: absolute;
            bottom: 0px;
            right: 0;
        }
    }

    .chart1 {
        right: 15px;
    }

    .chart2 {
        left: 15px;
    }

    .number-status-r {
        padding-left: 70px;
        text-align: left;
        position: relative;
    }

    .m-b {
        margin-bottom: 20px;
    }
</style>

